// -----------------------------------------------------------------------
//  <copyright file="RedisModule.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2024 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://www.dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2024-04-07 20:39</last-date>
// -----------------------------------------------------------------------

using System.ComponentModel;

using DaprPlus.Builder;
using DaprPlus.Extensions;
using DaprPlus.Configurations;

using Microsoft.Extensions.DependencyInjection;

using StackExchange.Redis;


namespace Shares.Infrastructure.Redis;

[Description("Redis Module")]
public class RedisModule : ModuleBase
{
    /// <summary>
    /// 获取 模块级别，级别越小越先启动
    /// </summary>
    public override ModuleLevel Level => ModuleLevel.Framework;

    /// <summary>
    /// 将模块服务添加到依赖注入服务容器中
    /// </summary>
    /// <param name="services">依赖注入服务容器</param>
    /// <returns></returns>
    public override IServiceCollection AddServices(IServiceCollection services)
    {
        services.Configure<RedisOptions>(RedisOptions.Position);
        var options = services.GetOptions<RedisOptions>(RedisOptions.Position);
        services.AddStackExchangeRedisCache(opts =>
        {
            opts.Configuration = options.Configuration;
            opts.InstanceName = options.InstanceName;
            if (options.DefaultDatabase.HasValue)
            {
                opts.ConfigurationOptions = new ConfigurationOptions
                {
                    EndPoints = { options.Configuration },
                    DefaultDatabase = options.DefaultDatabase,
                    Password = options.Password
                };
            }
        });

        return services;
    }
}
